import logging

from flask import Flask, g
from flask_migrate import Migrate
from flask_wtf import CSRFProtect
import config
import hooks
from exts import db, mail
from blueprints.online import bp as online_bp
from blueprints.offline import bp as offline_bp
from blueprints.business import bp as business_bp
import models

app = Flask(__name__)
# 数据库迁移的初始化
migrate = Migrate(app, db)
# 直接绑定配置文件
app.config.from_object(config.DevelopmentConfig)
db.init_app(app)
mail.init_app(app)
CSRFProtect(app)
# 绑定蓝图
app.register_blueprint(online_bp)
app.register_blueprint(offline_bp)
app.register_blueprint(business_bp)

# 绑定钩子函数
app.before_request(hooks.login_before_request)

"""配置基本日志记录"""
logging.basicConfig(filename="/opt/module/recommendSystem/log/app.log", level=logging.INFO)

"""Flask应用程序日志记录器"""
# 配置日志级别（例如，INFO，DEBUG，ERROR等）
app.logger.setLevel(logging.INFO)
# 创建文件处理器，将日志写入到指定文件中
file_handler = logging.FileHandler('/opt/module/recommendSystem/log/rating.log')
# file_handler = logging.FileHandler('log/rating.log')
file_handler.setLevel(logging.INFO)
# 创建日志格式器
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
# 将文件处理器添加到Flask应用程序的日志处理器中
app.logger.addHandler(file_handler)


# 上下文处理器（Context Processors）是一种用于在模板中提供全局变量或函数的机制。
@app.context_processor
def my_context_processor():
    return {"user": g.user}


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
